<template>
  <div class="clearfix">
    <a-upload
      v-model:file-list="fileList"
      action="https://upload-z1.qiniup.com"
      list-type="picture-card"
      @preview="handlePreview"
      :beforeUpload="beforeUpload"
      :maxCount="3"
      :data="uploadData"
      name="file"
    >
      <div v-if="fileList.length < 8">
        <plus-outlined />
        <div style="margin-top: 8px">Upload</div>
      </div>
    </a-upload>
    <a-modal
      :visible="previewVisible"
      :title="previewTitle"
      :footer="null"
      @cancel="handleCancel"
    >
      <img alt="example" style="width: 100%" :src="previewImage" />
    </a-modal>
  </div>
</template>
<script lang="ts" setup>
import { PlusOutlined } from '@ant-design/icons-vue'
import { reactive, ref } from 'vue'
import type { UploadProps } from 'ant-design-vue'
import { getUploadToken } from '@/api/upload'

import { defineExpose } from 'vue'

function getBase64(file: File) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => resolve(reader.result)
    reader.onerror = (error) => reject(error)
  })
}

const previewVisible = ref(false)
const previewImage = ref('')
const previewTitle = ref('')

let fileList = ref<any>([
  //   {
  //     uid: '-1',
  //     name: 'image.png',
  //     status: 'done',
  //     url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png'
  //   }
])
defineExpose({
  fileList,
  clear
})
//  取消
const handleCancel = () => {
  previewVisible.value = false
  previewTitle.value = ''
}
//  预览
const handlePreview = async (file: any) => {
  if (!file.url && !file.preview) {
    file.preview = (await getBase64(file.originFileObj)) as string
  }
  previewImage.value = file.url || file.preview
  previewVisible.value = true
  previewTitle.value =
    file.name || file.url.substring(file.url.lastIndexOf('/') + 1)
}
const uploadData = reactive({
  token: '',
  key: ''
})
//  beforeUpload

const beforeUpload = async (e: any) => {
  let {
    data: { token }
  } = await getUploadToken()

  let key = createKey(e)

  uploadData.key = key
  uploadData.token = token

  return true
}

const createKey = (e: File) => {
  let { type } = e

  return (
    Math.random().toString(16).slice(2) + +new Date() + '.' + type.split('/')[1]
  )
}

function clear() {
  fileList = ref<any>([])
}
</script>
<style>
/* you can make up upload button and sample style by using stylesheets */
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>
